package com.kimehwa.chapter2.Container2;

/**
 * @author xiaodongguan
 * @date 2022/02/23 07:41
 * @description 自己实现一个循环链表，连接操作就到常数时间
 **/
public class Container4 {

    private double amount;
    private Container4 next = this;


    public void addWater(double amount) {
        this.amount += amount;
    }



    public void connectTo(Container4 other) {
        // 这样组成了一个循环链表
        Container4 oldNext = next;
        next = other.next;
        other.next = oldNext;
    }

    public double getAmount() {
        updateGroup();
        return amount;
    }

    private void updateGroup() {
        //收集amount 与 count
        Container4 current = this;
        double totalAmount = 0;
        int groupSize = 0;
        do {
            totalAmount += current.amount;
            groupSize++;
            current = current.next;
        } while (current != this);
        double newAmount = totalAmount / groupSize;
        current = this;
        // 更新操作
        do {
            current.amount = newAmount;
            current= current.next;
        } while (current != this);

    }
}
